package com.second.service.impl;

import com.second.mapper.FHistoryMapper;
import com.second.mapper.FShopMapper;
import com.second.model.pojo.FHistory;
import com.second.model.pojo.FShop;
import com.second.service.IFHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
@Transactional
public class FHistoryServiceImpl implements IFHistoryService {

    @Autowired
    private FHistoryMapper historyMapper;

    @Autowired
    private FShopMapper shopMapper;

    @Override
    public FHistory addHistory(Integer userId, Integer shopId) {
        FHistory history = historyMapper.findByUserIdAndShopId(userId,shopId);
        if (null == history) {
            FHistory newHistory = new FHistory();
            newHistory.setUserId(userId);
            newHistory.setShopId(shopId);
            newHistory.setVisitedTime(new Date());
            return historyMapper.save(newHistory);
        }else {
            history.setVisitedTime(new Date());
            return historyMapper.save(history);
        }

    }

    @Override
    public List<FShop> findHistoryThree(Integer userId) {
        List<FHistory> list = historyMapper.findAllByUserIdOrderByVisitedTimeDesc(userId);
        List<FShop> historyList = new ArrayList<>();
        if (list.size()>=4){
            for (int i = 0; i < 4; i++) {
                FShop f = shopMapper.getById(list.get(i).getShopId());
                historyList.add(f);
            }
            return historyList;
        }else {
            for (FHistory h : list) {
                FShop f = shopMapper.getById(h.getShopId());
                historyList.add(f);
            }
            return historyList;
        }

    }
}
